package com.example.Utils;

import com.example.entity.StockTrade;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
@Slf4j
public class Env {
    public  DataStream<StockTrade>  getEnv(StreamExecutionEnvironment env) {

        env.setParallelism(1);

        // 创建 Kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("192.168.88.135:19092,192.168.88.135:29092,192.168.88.135:39092")
                .setTopics("stock-trades-")
                .setGroupId("stock-analysis-group")
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();
        log.info("数据源是"+source);



        // 创建数据流并添加水印
        DataStream<StockTrade> tradeStream = env
                .fromSource(
                        source,
                        WatermarkStrategy
                                .<String>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((event, timestamp) -> System.currentTimeMillis()),
                        "Kafka Source"
                )
                .map(new StockTradeMapper())
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<StockTrade>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                        .withTimestampAssigner((event, timestamp) -> event.getTime())
                );
        System.out.println(tradeStream);


        return tradeStream;
    }

}
